package cn.chia.back.action;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.chia.pojo.Address;
import cn.chia.pojo.User;
import cn.chia.service.IAddressService;
import cn.chia.service.IUserService;
import cn.chia.service.impl.UserServiceImpl;
import cn.chia.utils.FileUtils;
import cn.chia.utils.GetUserFromWeixin;

import com.opensymphony.xwork2.ActionSupport;

@Controller
@Scope(value="prototype")
public class UserAction extends ActionSupport{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger(UserAction.class);
	
	private User user;
	private List<User> userList;
	private int count;
	
	private IUserService userService;
	
	private int pageNo = 1;
	private int pageSize = 3;
	private String keyword = "";
	private String column = "tname";
	
	private File photo;
	private String photoFileName;
	
	private Address address;
	private String defaultAddress;
	private List<Address> allAddress;
	private IAddressService addressService;
	
	private Integer flag;
	
	private String code;
	
	private String tname;
	private String mob;
	
	/**
	 * 根据登录的用户ID，查询用户的相关信息
	 * @author:朱龙飞
	 * @throws Exception
	 */
	public String findById() throws Exception{
		User user1 = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		user = userService.findByWid(user1.getWid());
		ServletActionContext.getRequest().getSession().setAttribute("user", user);
		return "userInformation";
	}
	
	/**
	 * 更改用户信息前，先查询用户信息
	 * @author:朱龙飞
	 * @throws Exception
	 */
	public String updatePre() throws Exception{
		user = userService.findByWid(user.getWid());
		return "updateUser";
	}
	
	/**
	 * 更改用户信息
	 * @author:朱龙飞
	 * @throws Exception
	 */
	public String update() throws Exception{
		/*inputStream = conn.getInputStream();
		inputStreamReader = new InputStreamReader(inputStream, Charsets.UTF8);
		bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		StringBuffer buffer = new StringBuffer();
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		result = buffer.toString();*/
		//User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		//System.out.println(user.getUserid());
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		
		user.setTname( tname);
		user.setMob(mob);
		userService.update(user);
		return "userIndex";
	}
	
	/**
	 * 更改用户图片前，先查询用户图片
	 * @author:朱龙飞
	 * @throws Exception
	 */
	public String updatePhotoPre() throws Exception{
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		user = userService.findById(user.getUserid());
		return "updatePhoto";
		
	}
	
	/**
	 * 更改用户图片
	 * @author:朱龙飞
	 * @throws Exception
	 */
	public String updatePhoto() throws Exception{
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		//获得图片的保存地址
		String savePath = ServletActionContext.getServletContext().getRealPath("/upload")+"/";
		//如果用户没有选择图片就提交，则提示用户
		if(photoFileName==null){
			super.addActionError("您还没有选择图片");
			return "updatePhoto";
		}
		String fileName = FileUtils.saveFile(photo, savePath, photoFileName);
	
		user = userService.findById(user.getUserid());
		user.setPhoto(fileName);
		user.setTname(user.getTname());
		user.setMob(user.getMob());
	
		userService.update(user);
		return "userIndex";
	}
	
	/**
	 * 新增加一个用户，暂时没有用到
	 * @author:朱龙飞
	 * @throws Exception
	 */
	public String insert() throws Exception{
		userService.insert(user);
		return "success";
	}
	
	/**
	 * 根据用户名和手机号码验证用户登录，登录成功后将用户信息保存到session里
	 * @author:朱龙飞
	 * @throws Exception 
	 * @throws Exception
	 */
	public String login() throws Exception{
		
	
		User useron = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		if(useron != null){return "marketIndex";}
		String code = ServletActionContext.getRequest().getParameter("code");
		System.out.println("login方法中的code："+code);
		logger.info("in login()" + code);
		
		String openId = GetUserFromWeixin.returnUserInfo(code);
		System.out.print("获取到的openid为："+openId);

		logger.info("opeinid is " + openId + ", code is " + code);

		ServletActionContext.getRequest().getSession().setAttribute("c",code);
		ServletActionContext.getRequest().getSession().setAttribute("openid",openId);
		if (userService.findByWid(openId) == null) {
			User user = new User();
				user.setWid(openId);
				userService.insert(user);
		}
		User user1 = userService.findByWid(openId);
		ServletActionContext.getRequest().getSession().setAttribute("user", user1);
		System.out.println("session中的wid："+user1.getWid());
		
		
		return "marketIndex";
		
		}
			
	/**
	 * 查询用户的默认地址，用户与地址是一对多的关系
	 * @author:朱龙飞
	 * @throws Exception
	 */
	public String myAddress() throws Exception{
		//如果从购物车跳转到查询地址页面，则flag=1; 从用户信息跳转到查询号地址页面，则flag=0;
		

		User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		user.setFlag(flag);
		userService.update(user);
		allAddress = addressService.findAllAddress(user.getUserid());
		address = addressService.findByIdAndFlag(user.getUserid(), 1);
		
		
		
		//如果用户是首次登录则用户对应的地址列表为空，跳转到添加地址页面。
		if(user.getAddresses().size()==0){
			return "addAddress";
		}
		return "myAddress";
		
	}
	
	/**
	 * 添加用户地址
	 * @author:朱龙飞
	 * @throws Exception
	 */
	public String addAddress() throws Exception{
		User user1 = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		user = userService.findById(user1.getUserid());
		allAddress = addressService.findAllAddress(user.getUserid());
		
		//如果用户地址为空，则将首次添加的地址设为默认地址
		if(user.getAddresses().size()==0){
			address.setFlag(1);  //flag==1表示该地址为默认地址。
		}else{ 
			if(flag==null){
				//如果该用户对应的地址表里已经存在地址，则根据前台传回的flag值判断是否将新增的地址高为默认地址，flag==null，表示新增地址为非默认地址
				address.setFlag(0); 
				}else{
					//如果flag不为空，则遍历列表将已存在的默认地址设为非默认地址。将新增加的地址设为默认地址。
					for(int i=0; i<allAddress.size(); i++){
						if(allAddress.get(i).getFlag()==1){
							allAddress.get(i).setFlag(0);
						}
						
						address.setFlag(1);
					}
				}
			}
		//将userid和tname保存到地址表。
		address.setUser(user);
		address.setTname(user.getTname());
		
		addressService.saveAddress(address);
		address = addressService.findByIdAndFlag(user.getUserid(), 1);
		allAddress = addressService.findAllAddress(user.getUserid());
		return "myAddress";
	}
	/**
	 * 更改地址前先查询到地址
	 * @author 朱龙飞
	 * @throws Exception
	 */
	public String updatePreAddress() throws Exception{
		address = addressService.findById(address.getAddrId());
		return "updateAddress";
	}

	/**
	 * 更改地址信息
	 * @author 朱龙飞
	 * @throws Exception
	 */
	public String updateAddress() throws Exception{
		//根据session中的用户信息查询到该用户
		User user1 = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		user = userService.findById(user1.getUserid());
		allAddress = addressService.findAllAddress(user.getUserid());
		
		//如果没有将该地址更改为默认地地
		if(flag==null){
			address.setFlag(0);
			}else{
				//将该地址更改为默认地址
				for(int i=0; i<allAddress.size(); i++){
					if(allAddress.get(i).getFlag()==1){
						allAddress.get(i).setFlag(0);
					}
					address.setFlag(1);
				}
			}
		
		address.setUser(user);
		address.setTname(user.getTname());
		
		addressService.updateAddress(address);
		
		address = addressService.findByIdAndFlag(user.getUserid(), 1);
		user.setDefaultaddress(address.getAddr());
		allAddress = addressService.findAllAddress(user.getUserid());
		
		return "myAddress";
	}
	
	/**
	 * 根据addrId删除地址信息
	 * @author 朱龙飞 
	 * @throws Exception
	 */
	public String deleteAddress() throws Exception{
		User user1 = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		user = userService.findById(user1.getUserid());
		addressService.deleteAddress(address.getAddrId());
		address = addressService.findByIdAndFlag(user.getUserid(), 1);
		allAddress = addressService.findAllAddress(user.getUserid());
		return "myAddress";
	}
	
	
	/**
	 * 选择配送地址
	 * @author 朱龙飞
	 * @throws Exception
	 */
	public String selectAddress() throws Exception{
		address = addressService.findById(address.getAddrId());
		ServletActionContext.getRequest().getSession().setAttribute("address", address);
		return "selectedAddress";
	}
	
	public String selectPinAddress() throws Exception{
		address = addressService.findById(address.getAddrId());
		ServletActionContext.getRequest().getSession().setAttribute("address", address);
		return "selectPinAddress";
	}
	
	
	
	
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	@Resource(name="userServiceImpl")
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String getColumn() {
		return column;
	}

	public void setColumn(String column) {
		this.column = column;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public File getPhoto() {
		return photo;
	}

	public void setPhoto(File photo) {
		this.photo = photo;
	}

	public String getPhotoFileName() {
		return photoFileName;
	}

	public void setPhotoFileName(String photoFileName) {
		this.photoFileName = photoFileName;
	}

	public List<Address> getAllAddress() {
		return allAddress;
	}

	public void setAllAddress(List<Address> allAddress) {
		this.allAddress = allAddress;
	}
	
	@Resource(name="addressServiceImpl")
	public void setAddressService(IAddressService addressService) {
		this.addressService = addressService;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public String getDefaultAddress() {
		return defaultAddress;
	}

	public void setDefaultAddress(String defaultAddress) {
		this.defaultAddress = defaultAddress;
	}

	public Integer getFlag() {
		return flag;
	}

	public void setFlag(Integer flag) {
		this.flag = flag;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getTname() {
		return tname;
	}

	public void setTname(String tname) {
		this.tname = tname;
	}

	public String getMob() {
		return mob;
	}

	public void setMob(String mob) {
		this.mob = mob;
	}
	
	

	
	



	


	
	
	
	
	

	
	


	
	
	
	
	
}
